package remote.utils
{
	import flash.display.DisplayObject;
	import flash.display.InteractiveObject;
	import flash.display.Stage;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Vector3D;
	import flash.utils.getTimer;
	
	/**
	 * 鼠标移动速度测量
	 *
	 * @author 银魂飞雪
	 * @date 2011-9-15
	 */
	public class MouseSpeedMeasure
	{
		private var _target:DisplayObject;
		
		private var _lastPosition:Point;
		private var _currentPosition:Point;
		private var _lastTime:Number;
		private var _currentTime:Number;
		private var _movedNumber:int = 0;
		public function MouseSpeedMeasure(target:DisplayObject)
		{
			_target = target;
		}
		
		public function start():void
		{
			_target.stage.addEventListener(MouseEvent.MOUSE_MOVE, target_mouseMoveHandler);
			_lastPosition = new Point(_target.mouseX, _target.mouseY);
			_currentPosition = new Point(_target.mouseX, _target.mouseY);
			_currentTime = _lastTime = getTimer();
		}
		
		public function stop():void
		{
			_target.stage.removeEventListener(MouseEvent.MOUSE_MOVE, target_mouseMoveHandler);
		}
		
		public function get speed():Vector3D
		{
			var timeGap:Number = _currentTime - _lastTime;
			if(timeGap <= 0)
				return new Vector3D();
			return new Vector3D((_currentPosition.x - _lastPosition.x) / timeGap, (_currentPosition.y - _lastPosition.y) / timeGap);
		}
		
		protected function target_mouseMoveHandler(event:MouseEvent):void
		{
			if(++_movedNumber == 5)
			{
				_lastPosition.x = _currentPosition.x;
				_lastPosition.y = _currentPosition.y;
				_lastTime = _currentTime;
				
				_currentPosition.x = _target.mouseX;
				_currentPosition.y = _target.mouseY;
				_currentTime = getTimer();
				_movedNumber = 0;
			}
		}
	}
}